import axios from 'axios'
import EventEmitter from './EventEmitter.js'

const server = axios.create({
    baseURL: import.meta.env.VITE_API_URL
})

server.interceptors.request.use(config => {
    return config;
}, error => {
    return Promise.reject(error);
});

server.interceptors.response.use(response => {
    if(response.status === 200){
        if(response.data.code === 400){            
            return EventEmitter.emit('API:UN_AUTH')
        }
        return response.data
    }
    EventEmitter.emit('API_ERROR', response)
}, error => {
    return Promise.reject(error);
});

export const apiGet = (url, params) =>  server({ url, method:'get', params})

export const apiPost = (url, data) =>  server({ url, method:'post', data })

export const apiPut = (url, data) => server({ url, method:'put', data })

export const apiDel = (url, params) => server({ url, method:'delete', params })

export const apiStream = (url, params) => server({ url, method:'get', params, responseType: 'stream' })

// 上传文件,并 上传进度
export const apiUpload = (url, data) =>{
    return server({ url, method:'post', data, headers: { 'Content-Type': 'multipart/form-data' }, 
        onUploadProgress: (progressEvent) => {
            console.log(progressEvent)
        }
    })
}